﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Interactivity;


//Code authored by: Aaron
//About :http://www.wiredprairie.us/blog/index.php/about 
//Site: http://www.wiredprairie.us/blog/index.php/archives/847
namespace Tanagram.Behaviors.Touch.Silverlight
{
    public class AutoClipBehavior : Behavior<DependencyObject>
    {
        private RectangleGeometry _rectGeo;

        protected override void OnAttached()
        {
            base.OnAttached();

            if (base.AssociatedObject is FrameworkElement)
            {
                FrameworkElement fe = AssociatedObject as FrameworkElement;
                fe.SizeChanged += new SizeChangedEventHandler(AttachedObjectSizeChanged);

                _rectGeo = new RectangleGeometry();
                fe.Clip = _rectGeo;

                OnAdjustClip(fe, new Size(fe.ActualWidth, fe.ActualHeight));
            }
        }

        protected virtual void OnAdjustClip(FrameworkElement fe, Size sz)
        {
            Rect rect = new Rect(0, 0, sz.Width, sz.Height);

            // it would be interesting to handle the border, but alas
            // we can't as it would clip the border as well. :)
            // best solution is to just put the border on or around
            // the panel being clipped by this
            _rectGeo.Rect = rect;
        }

        private void AttachedObjectSizeChanged(object sender, SizeChangedEventArgs e)
        {
            OnAdjustClip(AssociatedObject as FrameworkElement, e.NewSize);
        }

        // always clean up after yourself ... remove anything that was attached
        // to prevent incorrect clipping and unnecessary event handlers
        protected override void OnDetaching()
        {
            base.OnDetaching();

            if (base.AssociatedObject is FrameworkElement)
            {
                FrameworkElement fe = AssociatedObject as FrameworkElement;
                fe.SizeChanged -= new SizeChangedEventHandler(AttachedObjectSizeChanged);
                fe.Clip = null;
                _rectGeo = null;
            }
        }
    }
}